package cn.net.xyan.easy.gwt.client.event;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.ui.Widget;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zarra on 16/2/17.
 */
public class ActionEvent<T> extends GwtEvent< ActionHandler<T> >{

    Action<T> action;

    Class<T> tClass;

    static Map<Class,Type> map = new HashMap<Class, Type>();


    //static List<Type> classes = new LinkedList<Type>();

    public ActionEvent(Action<T> action,Class<T> tClass){
        this.action = action;
        this.tClass = tClass;
    }

    static public <V> Type getType(Class<V> cls){
        if (map.get(cls) == null){
            map.put(cls,new Type<ActionHandler<V>>());
        }
        Type type =  map.get(cls);
        return type;
    }

    static public <V> void fire(EventBus eventBus,Widget widget, V data){
        Action<V> action = new Action<V>(widget,data);
        ActionEvent<V> actionEvent = new ActionEvent<V>(action, (Class<V>) data.getClass());
        eventBus.fireEvent(actionEvent);
    }

    @Override
    public Type getAssociatedType() {
        Type type = map.get(this.tClass);
        return type;
        //return new Type<ActionHandler<T>>();
    }

    @Override
    protected void dispatch(ActionHandler<T> handler) {
        handler.onAction(action);
    }

}
